package com.ktwlrj.core.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * ip工具类
 *
 * @author zhouxuanhong
 * @date 2019-04-03 14:03
 * @since JDK1.8
 */
@Slf4j
public class IPUtils {
    private static final String UNKNOWN = "unknown";

    /**
     * 获取IP地址
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     *
     * @return String ${@link String}
     * @author zhouxuanhong
     * @date 2019-04-03 14:05
     */
    public static String getIpAddr() {
        HttpServletRequest request = ServletUtils.getRequest();
        String ip = "unknown";
        if (request != null) {
            try {
                String xIp = request.getHeader("X-Real-IP");
                ip = request.getHeader("X-Forwarded-For");
                if (StringUtils.isNotEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
                    //多次反向代理后会有多个ip值，第一个ip才是真实ip
                    int index = ip.indexOf(",");
                    if (index != -1) {
                        return ip.substring(0, index);
                    } else {
                        return ip;
                    }
                }
                ip = xIp;
                if (StringUtils.isNotEmpty(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
                    return ip;
                }
                if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_CLIENT_IP");
                }
                if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getHeader("HTTP_X_FORWARDED_FOR");
                }
                if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
                ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
            } catch (Exception e) {
                log.error("IPUtils ERROR ", e);
            }
        }
        return ip;
    }

}
